package com.example.demo.service;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class WebSocketIdleStateHandler extends IdleStateHandler {

    //默认读的空闲时间
    private static final int default_idle_time = 50;

    public WebSocketIdleStateHandler(){
        super(default_idle_time, 0, 0, TimeUnit.SECONDS);
    }

    /**
     * 指定心跳时间(秒)
     *
     * @param readerIdleTimeSeconds
     * @param writerIdleTimeSeconds
     * @param allIdleTimeSeconds
     */
    public WebSocketIdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
        super(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds);
    }

    @Override
    protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        //如果是读空闲
        if (evt.state().equals(IdleState.READER_IDLE)) {
            Channel channel = ctx.channel();
            log.info("服务端未检测到客户端【{}】的心跳包，强制关闭客户端！", channel.id());
            channel.close();
        }
        super.channelIdle(ctx, evt);
    }
}
